package com.ll.msmservice.controller;

import com.ll.commonUtils.R;
import com.ll.msmservice.service.MsmService;
import com.ll.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 2020/11/11 - 10:32
 */
@Api(description = "手机验证码API") //swagger界面提示
@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送短信的方法
    @ApiOperation(value = "发送短信,随机生成验证码") //swagger界面提示
    @GetMapping("send/{phone}")
    public R sendMsm(@ApiParam(name = "phone", value = "手机号", required = true) @PathVariable String phone){
        System.out.println("MsmController => sendMsm => 调用发送短信的方法接收者手机号: " + phone);

        //1.从redis中取验证码, 如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);

        if (!StringUtils.isEmpty(code)){
            return R.error().message("该验证码还没有失效,有效期默认5分钟");
        }

        //2.如果redis获取不到, 进行阿里云发送
        //生成随机值,传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);

        //调用service发送短信的方法
        boolean isSend = msmService.send(param, phone);

        if (isSend){
            //发送成功,把发送成功的验证码放到redis里面
            //设置有效时间,5分钟有效时间
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return R.ok().message("短信发送成功");
        }else {
            return R.error().message("短信发送失败");
        }
    }

    //发送短信的方法
    @ApiOperation(value = "发送短信,自定义验证码(测试使用,所发的验证码不会存入redis)") //swagger界面提示
    @GetMapping("send2/{phone}/{code}")
    public R sendMsmNotRedis(@ApiParam(name = "phone", value = "手机号", required = true)
                             @PathVariable("phone") String phone,
                             @ApiParam(name = "code", value = "自定义验证码", required = true)
                             @PathVariable("code") String code){

        Map<String, Object> param = new HashMap<>();
        param.put("code", code);

        //调用service发送短信的方法
        boolean isSend = msmService.send(param, phone);

        if (isSend){
            return R.ok().message("短信发送成功");
        }else {
            return R.error().message("短信发送失败");
        }
    }
}
